import json,os,hashlib
from abc import ABC

from handlers import BaseHandler
from model import HostComputer,User
from tornado.gen import coroutine
from forms import CreateHostForm
from utils.multithreading import executor
from tornado.stack_context import wrap
from tornado.options import options


class UploadFile(BaseHandler,ABC):
    def md5(self,fdata):
        hash_md5 = hashlib.md5(fdata)
        return hash_md5.hexdigest()

    def post(self):
        upload_path = options.file_path  # 文件的暂存路径
        file_metas = self.request.files.get('file',None)  # 提取表单中‘name’为‘file’的文件元数据
        if not file_metas:
            return self.finish({"status":False,"response":""})
        for meta in file_metas:
            filename = self.md5(meta['body'])
            file_path = os.path.join(upload_path,filename)
            with open(file_path,'wb') as up:
                up.write(meta['body'])
                # OR do other thing
            self.finish({"status":True,"response":filename})
            return
        self.finish({"status":False,"response":""})


class ManagerHost(BaseHandler):
    @coroutine
    def get(self):
        query = self.session.query(User).filter_by(id = self.user.get("id"))
        user = yield executor(wrap(query.first))
        response = []
        for host in user.hosts:
            response.append(host.to_dict())
        self.finish({"status":True,"response":response})

    @coroutine
    def post(self):
        body = json.loads(self.request.body)
        query = self.session.query(User).filter_by(id = body.get("user_id"))
        user = yield executor(wrap(query.first))
        ids = body.get("ids")
        by = self.session.query(HostComputer).filter(HostComputer.id.in_(ids))
        hosts = yield executor(wrap(by.all))
        user.hosts = hosts
        self.session.add(user)
        self.session.commit()
        self.finish({"status":True,"response":""})


class HostHandler(BaseHandler,ABC):
    @coroutine
    def get(self):
        query = self.session.query(HostComputer)
        hosts = yield executor(query.all)
        response = []
        for host in hosts:
            response.append(host.to_dict())
        self.finish({"status":True,"response":response})

    @coroutine
    def post(self):
        host_body = json.loads(self.request.body)
        form = CreateHostForm(**host_body)
        if form.validate():
            data = form.data
            if data.get("id") == None:
                host = HostComputer(**data)
                self.session.add(host)
                yield executor(wrap(self.session.commit))
            else:
                query = self.session.query(HostComputer).filter_by(id = form.data["id"])
                host = yield executor(wrap(query.first))
                host.update_value(**data)
                yield executor(wrap(self.session.commit))
            self.finish({"status":True,'response':host.to_dict()})
        else:
            self.finish({"status":False,'response':"有必选项未填"})

    @coroutine
    def delete(self):
        id = int(self.request.body)
        query = self.session.query(HostComputer).filter_by(id = id)
        host = yield executor(query.first)
        self.session.delete(host)
        yield executor(wrap(self.session.commit),*())
        self.finish({"status":True,'response':host.to_dict()})
